package com.hh.TreeQuestions;

import java.util.HashMap;

/**
 * @Author hanghao
 * @Date 2023/7/6 15:44
 * @Version 1.0
 * 从前序与中序遍历序列构造二叉树
 * middle
 */

public class No105 {
    HashMap<Integer, Integer> map = new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return findNode(preorder,0,preorder.length,inorder,0,inorder.length);
        //可以看出来我们使用的是前开后闭
    }
    public TreeNode findNode(int[] preorder, int preBegin, int preEnd, int[] inorder, int inBegin, int inEnd) {
        if (preBegin >=  preEnd || inBegin >= inEnd) return null;
        int rootIndex = map.get(preorder[0]);
        TreeNode root = new TreeNode(inorder[rootIndex]);
        int leftLen = rootIndex - inBegin;
        root.left = findNode(preorder,preBegin + 1, preBegin + 1 + leftLen, inorder,inBegin,rootIndex);
        root.right = findNode(preorder,preBegin + 1 + leftLen,preEnd,inorder,rootIndex + 1,inEnd);
        return root;
    }

}
